package entities;

import com.haxepunk.Entity;
import com.haxepunk.graphics.Spritemap;
import com.haxepunk.tmx.TmxObject;
import com.haxepunk.utils.Input;
import com.haxepunk.utils.Key;
import entities.*;

enum StateLegs
{
	IDLE; JUMP; REGRESS;
}

/**
 * ...
 * @author Marcelo Ruben Guardia
 */
class LegsRobot extends Entity
{
	private var spLeg:Spritemap;
	private var state:StateLegs;
	private var refProtobot:Protobot;

	public function new(obj:TmxObject) 
	{
		super(obj.x, obj.y);

		spLeg = new Spritemap(GC.IMG_legs, 128, 84);
		spLeg.add(IDLE.getName(), [0], 0, false);
		spLeg.add(JUMP.getName(), [1, 2, 3, 4, 5, 6, 7, 8, 9], 36, false);
		spLeg.add(REGRESS.getName(), [9, 8, 7, 6, 5, 4, 3, 2, 1], 36, false);
		state = IDLE;
		spLeg.play(state.getName());		
		spLeg.scale = 0.5;
		//setOrigin(32, 0);
		//spLeg.centerOrigin();
		spLeg.originX = 64;
		setHitbox(64, 25, 32, 0);
		
		graphic = spLeg;
		
		type = "legs_robot";
		layer = -1;
		refProtobot = null;
		
		Input.define("jump", [Key.SPACE]);//Key.W, Key.UP]);
	}
	
	override public function update():Void
	{

		super.update();
		
		switch(state)
		{
			case IDLE:
				setHitbox(64, 25, 32, 0);
			
			case JUMP:
				if (spLeg.complete)
					ChangeState(REGRESS);
				else
				 setHitbox(width - 2, height + 2, cast(left - 1, Int), 0);
					
			
			case REGRESS:
				if (spLeg.complete)
					ChangeState(IDLE);
				else
				 setHitbox(width + 2, height - 2, cast(left + 1, Int), 0);

		}
		
		if(refProtobot!=null)
		{
			x = refProtobot.x;
			y = refProtobot.y;
			
			if (refProtobot.GetState() == Protobot.StateProtobot.IDLE || refProtobot.GetState() == Protobot.StateProtobot.WALK)
			{
				if(Jumping())
				{
					ChangeState(StateLegs.JUMP);
					refProtobot.SetVelocity(refProtobot.GetVelocity().x,	-10);
					refProtobot.ChangeState(Protobot.StateProtobot.JUMP);
				}
				
				if (ChocaraPiso())
				{
					refProtobot.SetVelocity(refProtobot.GetVelocity().x,	0);
					refProtobot.ChangeState(Protobot.StateProtobot.JUMP);
				}
			}
		}
	}
	
	public function Jumping():Bool		{		return Input.check("jump");					}

	public function ChangeState(newState:StateLegs):Void
	{
		state = newState;
		spLeg.play(state.getName());
	}
	
	public function ChocaraPiso():Bool
	{
		return (collide("solid", x, y) != null || collide("platform", x, y) != null);
	}
	
	public function SetProtobot(proto:Protobot):Void
	{
		refProtobot = proto;
	}
	
}